/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain an copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.ms.banner.util;

import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

/**
 * 网络加载图片的Task类
 *
 * @since 2018-05-07
 */
class BitmapLoaderTask {
    HttpURLConnection connection = null;
    ImageSource.DecodingOptions decodingOptions = null;
    HashMap<String, PixelMap> tempPixeMap = null;
    private Callback callback;

    BitmapLoaderTask(String url, Callback callback) {
        this.callback = callback;
        getImg(url);
    }

    private void getImg(String urlImage) {
        if (tempPixeMap == null) {
            tempPixeMap = new HashMap<>();
        }
        PixelMap tmp = tempPixeMap.get(urlImage);
        if (tmp == null) {
            if (decodingOptions == null) {
                decodingOptions = new ImageSource.DecodingOptions();
                decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
            }
            try {
                URL url = new URL(urlImage);
                URLConnection urlConnection = url.openConnection();
                if (urlConnection instanceof HttpURLConnection) {
                    connection = (HttpURLConnection) urlConnection;
                }
                if (connection != null) {
                    connection.connect();

                    // 之后可进行url的其他操作
                    // 得到服务器返回过来的流对象
                    InputStream inputStream = urlConnection.getInputStream();
                    ImageSource imageSource = ImageSource.create(inputStream, new ImageSource.SourceOptions());

                    // 普通解码叠加旋转、缩放、裁剪
                    PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
                    callback.result(pixelMap);
                    tempPixeMap.put(urlImage, pixelMap);
                }
            } catch (IOException e) {
                callback.result(null);
            }
        } else {
            callback.result(tmp);
        }
    }

    /**
     * Callback
     *
     * @since 2018-05-07
     */
    interface Callback {
        void result(PixelMap bitmap);
    }
}
